package cn.gson.oasys;

import java.sql.*;

public class PGSQL {
    public static Connection GetConnection(String username, String passwd) {
        //驱动类。
        String driver = "org.postgresql.Driver";
        //数据库连接描述符。
        String sourceURL = "jdbc:postgresql://114.116.235.255:5432/oasys";
        Connection conn = null;
        try {
            //加载数据库驱动。
            Class.forName(driver).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        try {
            //创建数据库连接。
            //getConnection(String url, String user, String password)
            conn = DriverManager.getConnection(sourceURL, username, passwd);
            System.out.println("Connection succeed!");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return conn;
    };
    //执行查询SQL语句。
    public static void SelectTest(Connection conn) {
        Statement stmt = null;
        try {
            stmt = conn.createStatement();
            //执行SELECT语句。
            ResultSet rs = stmt.executeQuery("select * from aoa_attachment_list");
            while (rs.next()) {
                System.out.println("id:" + rs.getString(1) + ", c_name:" + rs.getString(2) + ", name:" + rs.getString(3));
            }

            stmt.close();
        } catch (SQLException e) {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        String userName = "postgres";
        String password = "Huawei@1234!@#$";
        //创建数据库连接。
        Connection conn = GetConnection(userName, password);
        //查询测试表。
        SelectTest(conn);
        //关闭数据库连接。
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}